<template>
  <div class="app-container">
    <el-form
      class="list-search"
      :model="queryParams"
      ref="queryRef"
      
      :inline="true"
      label-width="100"
    >
      <el-form-item label="请选择公司" prop="companyCode" v-if="user.userType != 2">
        <el-select
          v-model="queryParams.companyCode"
          placeholder="请选择公司"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in companyList"
            :key="dict.companyCode"
            :label="dict.companyName"
            :value="dict.companyCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title" >
        <el-input v-model="queryParams.questionnaireTitle" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="isActive" >
        <el-select
          v-model="queryParams.isPublished"
          placeholder="请选择状态"
          clearable
          style="width: 240px"
        >
          <el-option
            key="1"
            label="已发布"
            value="1"
          />
          <el-option
            key="0"
            label="未发布"
            value="0"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="search()"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Plus" @click="addDyn"> 新增 </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="questionnaireTitle" />
      <el-table-column
        label="归属公司"
        v-if="user.userType != 2"
        align="center"
        prop="tel"
      >
        <template #default="{ row }">
          {{
            filterName(
              companyList,
              row.companyCode,
              "companyCode",
              "companyName"
            )
          }}
        </template>
      </el-table-column>
      <el-table-column label="题库类型" align="center" prop="questionnaireType">
        <template #default="scope">
          {{ scope.row.questionnaireType == "1" ? "问卷" : "表单" }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <span v-if="scope.row.isPublished == 0" style="color: #f56c6c"
            >未发布</span
          >
          <span v-if="scope.row.isPublished == 1" style="color: #67c23a"
            >已发布</span
          >
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center" prop="price">
        <template #default="scope">
          {{ Number(scope.row.price).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" width="220">
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="scope.row.isPublished == 1"
            @click="editDyn(scope.row, 'see')"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="editDyn(scope.row)"
            v-else
          >
            修改
          </el-button>
          <el-button
            link
            :type="scope.row.isPublished == 0 ? 'primary' : 'danger'"
            @click="editPublished(scope.row)"
          >
            {{ scope.row.isPublished == 0 ? "发布" : "停用" }}
          </el-button>
          <el-popconfirm
            width="220"
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            v-if="scope.row.isPublished == 0"
            icon-color="#626AEF"
            title="是否删除"
            @confirm="del(scope.row)"
          >
            <template #reference>
              <el-button link type="danger"> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer
      :title="operationType == 'add' ? '添加服务问卷' : '服务问卷'"
      v-model="open"
      size="900px"
      append-to-body
    >
      <div class="dyn_content">
        <el-form
          ref="ruleFormRef"
          style="max-width: 900px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="标题" prop="questionnaireTitle">
            <el-input
              v-model="ruleForm.questionnaireTitle"
              :disabled="isEdit"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item
            label="服务所属公司"
            v-if="user.userType != 2"
            prop="companyCode"
          >
            <el-select
              v-model="ruleForm.companyCode"
              placeholder="请选择公司"
              clearable
              style="width: 240px"
              :disabled="isEdit"
            >
              <el-option
                v-for="dict in companyList"
                :key="dict.companyCode"
                :label="dict.companyName"
                :value="dict.companyCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="照片" prop="questionnaireImageUrl">
            <ImageUpload
              v-model="ruleForm.questionnaireImageUrl"
              :limit="1"
              :disabled="isEdit"
            ></ImageUpload>
          </el-form-item>
          <el-form-item label="题案类型" prop="questionnaireType">
            <el-select
              v-model="ruleForm.questionnaireType"
              placeholder="请选择类型"
              clearable
              :disabled="isEdit"
              style="width: 240px"
            >
              <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="发布状态" prop="isPublished">
          <el-radio-group v-model="ruleForm.isPublished">
            <el-radio value="1">发布</el-radio>
            <el-radio value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item> -->
          <el-form-item label="价格" prop="price">
            <el-input
              v-model="ruleForm.price"
              type="number"
              :disabled="isEdit"
              style="width: 240px"
            ></el-input>
          </el-form-item>
          <div>题目列表：</div>
          <br />
          <div class="list_item" v-for="(itg, index) in ruleForm.questionList">
            <div class="no-list">题目{{ index + 1 }}:</div>
            <div
              class="del"
              @click="delList(ruleForm.questionList, index)"
              v-if="!isEdit"
            >
              <el-icon>
                <CircleCloseFilled />
              </el-icon>
            </div>
            <el-form-item
              label="题目标题"
              :prop="`questionList[${index}].questionTitle`"
              :rules="[
                { required: true, message: '请填写标题', trigger: 'blur' },
              ]"
            >
              <el-input v-model="itg.questionTitle" :disabled="isEdit" />
            </el-form-item>
            <el-form-item
              label="是否必填"
              :prop="`questionList[${index}].isRequired`"
              :rules="[
                { required: true, message: '请选择是否必填', trigger: 'blur' },
              ]"
            >
              <el-radio-group v-model="itg.isRequired" :disabled="isEdit">
                <el-radio value="1">必填</el-radio>
                <el-radio value="0">不必填</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="答案类型"
              :prop="`questionList[${index}].questionType`"
              :rules="[
                { required: true, message: '请选择答案类型', trigger: 'blur' },
              ]"
            >
              <el-radio-group
                v-model="itg.questionType"
                :disabled="isEdit"
                @change="changeQuestionType(itg)"
              >
                <el-radio value="1">单选</el-radio>
                <el-radio value="2">多选</el-radio>
                <el-radio value="3">文本</el-radio>
                <el-radio value="4">时间</el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-if="itg.questionType == 1 || itg.questionType == 2">
              <div v-for="(n, i) in itg.questionOptionList">
                <el-form-item :label="`答案${i + 1}:`" prop="itg.type">
                  <el-input
                    class="answer_input"
                    v-model="n.optionContent"
                    :disabled="ruleForm.isPublished == 1"
                  ></el-input>
                  <el-button
                    type="primary"
                    @click="addAnswer(itg.questionOptionList)"
                    v-if="!isEdit"
                  >
                    新增
                  </el-button>
                  <el-button
                    type="danger"
                    v-if="!isEdit"
                    @click="delAnswer(itg.questionOptionList, i)"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
            </div>
            <!-- <div v-if="itg.radio == 3">
            <el-form-item label="正则验证" prop="itg.rule">
              <el-input v-model="itg.rule" />
            </el-form-item>
          </div> -->
          </div>
          <div class="addList">
            <el-button type="primary" @click="addList" v-if="!isEdit"
              >新增题目</el-button
            >
          </div>
        </el-form>
        <div class="dist_btn">
          <el-button type="primary" plain @click="open = false">取消</el-button>
          <el-button type="primary" @click="save" :disabled="isEdit"
            >确定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="WebsiteUser">
import {
  queryBasicCompany,
  questionnaireInsert,
  questionnaireQuery,
  queryDetails,
  questionnaireUpdate,
  questionnaireDelete,
  updatePublished,
} from "@/api/website/index";
import { InfoFilled } from "@element-plus/icons-vue";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import { computed } from "vue";
let user = useUserStore();

let loading = ref(false);
let dataList = ref([]);
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0);
// 获取公司列表
let companyList = ref([]);
function getCompanyList() {
  queryBasicCompany({
    pageNum: 1,
    pageSize: 999,
  }).then((res) => {
    companyList.value = res.rows;
  });
}
getCompanyList();
let typeList = ref([
  { id: "1", name: "问卷" },
  { id: "2", name: "表单" },
]);
// 保存 编辑
let operationType = ref("add");
function addDyn() {
  open.value = true;
  operationType.value = "add";
  ruleForm.value = {
    companyCode: user.userType == 2 ? user.companyCode : "",
    questionList: [{ questionOptionList: [{ optionContent: "" }] }],
  };
}
function del(row) {
  questionnaireDelete(row.id).then((res) => {
    ElMessage.success("删除成功");
    getList();
  });
}
// 是否能编辑
// function isEdit() {
//   console.log(ruleForm.value.isPublished == 1 || modelType.value == "see");

// }
let isEdit = computed(() => {
  return ruleForm.value.isPublished == 1 || modelType.value == "see";
});
function editPublished(row) {
  ElMessageBox.confirm("是否修改状态?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      updatePublished(row.id).then((res) => {
        ElMessage.success("修改状态成功");
        getList();
      });
    })
    .catch(() => {});
}
let modelType = ref("");
function editDyn(row, type) {
  modelType.value = type;
  operationType.value = "edit";
  ruleForm.value = {};
  queryDetails(row.id).then((res) => {
    open.value = true;
    ruleForm.value = res.data;
  });
}
function refresh() {
  queryParams.value.pageNum = 1;
  queryParams.value.companyCode = "";
  queryParams.value.questionnaireTitle = "";
  queryParams.value.isPublished = null;
  getList();
}
function changeQuestionType(itg) {
  if (
    (itg.questionType == 1 || itg.questionType == 2) &&
    !itg.questionOptionList
  ) {
    itg.questionOptionList = [{ optionContent: "" }];
  }
}
// 获取页面列表
function getList() {
  loading.value = true;
  questionnaireQuery(queryParams.value)
    .then((res) => {
      dataList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}
getList();
function search() {
  queryParams.value.pageNum = 1;
  getList();
}
let open = ref(false);
let ruleFormRef = ref(null);
let ruleForm = ref({
  questionList: [{ questionOptionList: [{ optionContent: "" }] }],
});
let rules = ref({
  questionnaireTitle: [
    { required: true, message: "请填写标题", trigger: "blur" },
  ],
  questionnaireImageUrl: [
    { required: true, message: "请上传图片", trigger: "blur" },
  ],
  questionnaireType: [
    { required: true, message: "请选择服务类型", trigger: "blur" },
  ],
  // isPublished: [{ required: true, message: "请选择是否发布", trigger: "blur" }],
  companyCode: [
    { required: true, message: "请选择服务所属公司", trigger: "blur" },
  ],
  price: [{ required: true, message: "请填写价格", trigger: "blur" }],
});
function addAnswer(list) {
  list.push({ title: "" });
}
function delAnswer(list, i) {
  list.splice(i, 1);
}
function addList() {
  ruleForm.value.questionList.push({
    questionOptionList: [{ optionContent: "" }],
  });
}
function delList(list, i) {
  list.splice(i, 1);
}
// 保存
function save() {
  ruleFormRef.value.validate((res) => {
    if (!res) return;
    let data = JSON.parse(JSON.stringify(ruleForm.value));
    data.questionList.forEach((item, index) => {
      let arr = [];
      if (
        item.questionOptionList &&
        (item.questionType == 1 || item.questionType == 2)
      ) {
        arr = item.questionOptionList.filter((itg) => itg.optionContent);
      }
      data.questionList[index].questionOptionList =
        arr.length == 0 ? null : arr;
    });
    if (operationType.value == "add") {
      questionnaireInsert(data)
        .then((res) => {
          ElMessage.success("添加成功");
          getList();
          open.value = false;
        })
        .catch((err) => {
          open.value = false;
        });
    } else {
      let data = JSON.parse(JSON.stringify(ruleForm.value));
      if (data.isPublished == 1) {
        ElMessage.info("已发布，不能修改");
        return;
      }
      data.questionList.forEach((item, index) => {
        let arr = [];
        if (
          item.questionOptionList &&
          (item.questionType == 1 || item.questionType == 2)
        ) {
          arr = item.questionOptionList.filter((itg) => itg.optionContent);
        }
        data.questionList[index].questionOptionList =
          arr.length == 0 ? null : arr;
      });
      questionnaireUpdate(data)
        .then((res) => {
          ElMessage.success("修改成功");
          getList();
          open.value = false;
        })
        .catch((err) => {
          open.value = false;
        });
    }
  });
}
</script>

<style scoped lang="scss">
.userImg {
  width: 50px;
  height: 50px;
}

.no-list {
  font-size: 14px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
  padding-left: 10px;
}

.list_item {
  border: 1px dotted #ddd;
  padding: 10px;
  border-radius: 10px;
  margin-bottom: 12px;
  position: relative;

  .del {
    position: absolute;
    top: -8px;
    right: -8px;
    color: #f56c6c;
  }
}

.addList {
  text-align: right;
}

.answer_input {
  width: 250px;
  margin-right: 20px;
}
.dist_btn {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: white;
  box-shadow: -3px -3px 6px #ccc;
  padding: 10px 0;
}
.dyn_content {
  padding-bottom: 90px;
}
</style>
